/**
 * 
 */
package com.erlang4j.internal.process;

import com.ericsson.otp.erlang.OtpErlangObject;
import com.ericsson.otp.erlang.OtpErlangPid;
import com.erlang4j.api.exceptionHandler.IExceptionHandler;
import com.erlang4j.internal.basicIo.IBasicMailBox;

/**
 * <p>
 * This is the thread that listens to a mailbox and processes messages that it receives. Please don't create it
 * directly, instead create it from IMessageProcessor
 * </p>
 * 
 * @author Phil Rice
 */
public class MessageProcessorThread extends Thread {
	private final StateMachine messageProcessor;
	private final IExceptionHandler handler;
	private boolean cont = true;
	private final IBasicMailBox basicOperations;

	public MessageProcessorThread(StateMachine messageProcessor, IBasicMailBox basicOperations, IExceptionHandler handler) {
		this.messageProcessor = messageProcessor;
		this.basicOperations = basicOperations;
		this.handler = handler;
	}

	@Override
	public void run() {
		try {
			while (cont) {
				OtpErlangObject receive = basicOperations.receive(10);
				if (receive != null)
					this.messageProcessor.process(receive);
			}
		} catch (ThreadDeath e) {
			throw e;
		} catch (Throwable e) {
			handler.process(e);
		}
	}

	public void terminate() {
		cont = false;
		try {
			join();
		} catch (InterruptedException e) {
		}
	}

	public OtpErlangPid pid() {
		return basicOperations.self();
	}
}